package com.uuticketweb.ticket.util;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ArrayUtils;

public class MyUtils {
	public static String[] listToArray(List strList) {
		if(strList == null || strList.isEmpty()) {
			return null;
		}
		String[] result = new String[strList.size()];
		for(int i = 0; i < strList.size(); i ++) {
			result[i] = (String)strList.get(i);
		}
		return result;
	}
	
	public static String[] removeDuplicatedElement(String[] strArr) {
		String[] res = new String[]{};
		for(int i = 0; i < strArr.length; i ++) {
			if(!ArrayUtils.contains(res, strArr[i])) {
				res = (String[])ArrayUtils.add(res, strArr[i]);
			}
		}
		return res;
	}
	
	/**
     * 手动解析并解码http请求的参数
     * @param request http请求
     * @param paraName 参数的名称
     * @param charSet 字符集
     * @return
     */
    public static String getUrlDecodedRequestParameter(HttpServletRequest request, String paraName, String charSet) {

		if(paraName == null || paraName.trim().length() == 0)
			throw new IllegalArgumentException("paraName can not be empty");
		String parameter = paraName.trim();
		String querystring = request.getQueryString();
		if(querystring == null) return null;
		int pos = querystring.indexOf("&" + parameter + "=");
		if(pos == -1) {
			pos = querystring.indexOf(parameter + "=");
		}
		if(pos == -1) return "";
		int nextpos = querystring.indexOf("&", pos + 1);
		String encodedWhere;
		if(nextpos != -1) {
			encodedWhere = querystring.substring(pos, nextpos);
		} else {
			encodedWhere = querystring.substring(pos);
		}
		encodedWhere = encodedWhere.substring(encodedWhere.indexOf("=") + 1);
		String decodedString = encodedWhere;
		try {
			decodedString = URLDecoder.decode(encodedWhere, charSet);
		} catch (UnsupportedEncodingException e) {
			// ignore this exception
		}
		return decodedString;
	}
}
